package com.banfan.almond.web.annotation.OperationLogger;


import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Slf4j
@Aspect
@Component
public class OperationLoggerAspect {

    @Pointcut(value = "@annotation(operationLogger)")
    public void pointcut(OperationLogger operationLogger) {

    }

    @Around(value = "pointcut(operationLogger)")
    public Object doAround(ProceedingJoinPoint joinPoint, OperationLogger operationLogger) throws Throwable {

        Object result = joinPoint.proceed();

        handle(joinPoint);

        return result;

    }

    private void handle(ProceedingJoinPoint joinPoint) throws NoSuchMethodException {

        //获取请求数据
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String remoteAddr = request.getRemoteAddr();
        String httpMethod = request.getMethod();
        StringBuffer requestURL = request.getRequestURL();
        String UA = request.getHeader("User-Agent");

        //获取操作数据
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method currentMethod = joinPoint.getTarget().getClass().getMethod(signature.getName(), signature.getParameterTypes());

        OperationLogger annotation = currentMethod.getAnnotation(OperationLogger.class);
        boolean save = annotation.save();//保存到数据库
        String operation = annotation.operation();


        log.info("{} | {} - {} | {} - {}", operation, remoteAddr, httpMethod, requestURL, UA);


    }

}
